// 学习进度追踪页面交互功能
document.addEventListener('DOMContentLoaded', function() {
    // 初始化时间范围选择
    initTimeRangeSelector();

    // 初始化准确率指示器
    initAccuracyIndicators();

    // 初始化活动日历交互
    initActivityCalendar();

    // 初始化图表
    initProgressCharts();

    // 绑定导出功能
    bindExportFunctionality();

    // 初始化洞察计算
    calculateLearningInsights();
});

// 初始化时间范围选择
function initTimeRangeSelector() {
    const rangeButtons = document.querySelectorAll('.range-btn');
    const currentDays = parseInt(document.querySelector('.time-range-selector').dataset.currentDays) || 30;

    rangeButtons.forEach(button => {
        const buttonDays = parseInt(button.dataset.days);

        // 设置当前激活状态
        if (buttonDays === currentDays) {
            button.classList.add('active');
        }

        // 点击事件
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const days = this.dataset.days;
            updateTimeRange(days);
        });
    });
}

// 更新时间范围
function updateTimeRange(days) {
    // 显示加载状态
    showLoadingState();

    // 构建新的URL
    const url = new URL(window.location.href);
    url.searchParams.set('days', days);

    // 跳转到新URL
    setTimeout(() => {
        window.location.href = url.toString();
    }, 500);
}

// 初始化准确率指示器
function initAccuracyIndicators() {
    const accuracyIndicators = document.querySelectorAll('.accuracy-fill');

    accuracyIndicators.forEach(indicator => {
        const accuracy = parseFloat(indicator.dataset.accuracy);
        const color = getAccuracyColor(accuracy);

        // 设置颜色和宽度
        indicator.style.width = (accuracy * 100) + '%';
        indicator.style.background = color;

        // 设置父元素的颜色
        const valueElement = indicator.closest('.accuracy-indicator').querySelector('.accuracy-value');
        if (valueElement) {
            valueElement.style.color = color;
            valueElement.textContent = (accuracy * 100).toFixed(1) + '%';
        }
    });
}

// 根据准确率获取颜色
function getAccuracyColor(accuracy) {
    if (accuracy >= 0.8) return '#28a745';
    if (accuracy >= 0.6) return '#ffc107';
    return '#dc3545';
}

// 初始化活动日历交互
function initActivityCalendar() {
    const activityDays = document.querySelectorAll('.activity-day');

    activityDays.forEach(day => {
        day.addEventListener('click', function() {
            // 移除其他天的激活状态
            activityDays.forEach(d => d.classList.remove('active'));

            // 设置当前天激活
            this.classList.add('active');

            // 显示该天的详细活动
            showDayDetails(this.dataset.date);
        });

        // 悬停效果
        day.addEventListener('mouseenter', function() {
            if (!this.classList.contains('active')) {
                this.style.transform = 'translateY(-2px)';
                this.style.boxShadow = '0 4px 15px rgba(0, 0, 0, 0.1)';
            }
        });

        day.addEventListener('mouseleave', function() {
            if (!this.classList.contains('active')) {
                this.style.transform = 'translateY(0)';
                this.style.boxShadow = 'none';
            }
        });
    });
}

// 显示某天的详细活动
function showDayDetails(date) {
    // 这里可以实现显示某天详细活动的逻辑
    // 例如：弹出模态框、更新详细列表等
    console.log('显示日期详情:', date);

    // 示例：高亮对应日期的表格行
    const tableRows = document.querySelectorAll('.activity-table tbody tr');
    tableRows.forEach(row => {
        if (row.cells[0].textContent === date) {
            row.style.background = '#f8fff9';
            row.scrollIntoView({ behavior: 'smooth', block: 'center' });
        } else {
            row.style.background = '';
        }
    });
}

// 初始化图表
function initProgressCharts() {
    // 这里可以使用Chart.js或其他图表库
    // 初始化学习活动趋势图
    initActivityTrendChart();

    // 初始化准确率趋势图
    initAccuracyTrendChart();
}

// 初始化学习活动趋势图
function initActivityTrendChart() {
    const ctx = document.getElementById('activityTrendChart');
    if (!ctx) return;

    // 示例Chart.js代码
    /*
    const activities = JSON.parse(document.getElementById('activityData').textContent);

    new Chart(ctx, {
        type: 'line',
        data: {
            labels: activities.map(a => a.date),
            datasets: [{
                label: '练习数量',
                data: activities.map(a => a.total_practices),
                borderColor: '#007bff',
                backgroundColor: 'rgba(0, 123, 255, 0.1)',
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: {
                    position: 'top',
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: '练习数量'
                    }
                }
            }
        }
    });
    */
}

// 初始化准确率趋势图
function initAccuracyTrendChart() {
    const ctx = document.getElementById('accuracyTrendChart');
    if (!ctx) return;

    // 类似的Chart.js代码
}

// 绑定导出功能
function bindExportFunctionality() {
    const exportBtn = document.getElementById('exportProgressData');
    if (exportBtn) {
        exportBtn.addEventListener('click', exportProgressData);
    }
}

// 导出进度数据
function exportProgressData() {
    const activities = JSON.parse(document.getElementById('activityData').textContent);
    const totalStats = JSON.parse(document.getElementById('totalStatsData').textContent);

    const exportData = {
        exportTime: new Date().toISOString(),
        timeRange: document.querySelector('.time-range-selector').dataset.currentDays + '天',
        totalStats: totalStats,
        dailyActivities: activities
    };

    const dataStr = JSON.stringify(exportData, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});

    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `learning-progress-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    URL.revokeObjectURL(url);

    showNotification('学习进度数据导出成功！', 'success');
}

// 计算学习洞察
function calculateLearningInsights() {
    const activities = JSON.parse(document.getElementById('activityData').textContent);

    if (activities.length === 0) return;

    // 计算连续学习天数
    const consecutiveDays = calculateConsecutiveDays(activities);

    // 计算平均准确率
    const avgAccuracy = activities.reduce((sum, activity) => sum + activity.accuracy, 0) / activities.length;

    // 计算最佳学习日
    const bestDay = activities.reduce((best, current) =>
        current.total_practices > best.total_practices ? current : best
    );

    // 更新洞察显示
    updateInsightDisplay('consecutive-days', consecutiveDays, '连续学习天数');
    updateInsightDisplay('avg-accuracy', (avgAccuracy * 100).toFixed(1) + '%', '平均准确率');
    updateInsightDisplay('best-day', bestDay.total_practices, '单日最高练习量');
}

// 计算连续学习天数
function calculateConsecutiveDays(activities) {
    if (activities.length === 0) return 0;

    const dates = activities.map(a => new Date(a.date)).sort((a, b) => a - b);
    let maxConsecutive = 1;
    let currentConsecutive = 1;

    for (let i = 1; i < dates.length; i++) {
        const diffTime = dates[i] - dates[i - 1];
        const diffDays = diffTime / (1000 * 60 * 60 * 24);

        if (diffDays === 1) {
            currentConsecutive++;
            maxConsecutive = Math.max(maxConsecutive, currentConsecutive);
        } else {
            currentConsecutive = 1;
        }
    }

    return maxConsecutive;
}

// 更新洞察显示
function updateInsightDisplay(elementId, value, description) {
    const element = document.getElementById(elementId);
    if (element) {
        element.querySelector('.insight-value').textContent = value;
        element.querySelector('.insight-description').textContent = description;
    }
}

// 显示加载状态
function showLoadingState() {
    const mainContent = document.querySelector('.container');
    const loadingOverlay = document.createElement('div');
    loadingOverlay.className = 'loading-state';
    loadingOverlay.innerHTML = '<div class="loading-spinner"></div>';
    loadingOverlay.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(255, 255, 255, 0.8);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 9999;
    `;

    document.body.appendChild(loadingOverlay);
}

// 显示通知
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show`;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 300px;
    `;
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.body.appendChild(notification);

    // 自动移除通知
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}

// 初始化所有功能
function initializeAll() {
    initTimeRangeSelector();
    initAccuracyIndicators();
    initActivityCalendar();
    initProgressCharts();
    bindExportFunctionality();
    calculateLearningInsights();
}

// 添加到全局作用域
window.exportProgressData = exportProgressData;

// 页面加载完成后初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeAll);
} else {
    initializeAll();
}